<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        html,body{
            width: 100%;
            height: 100%;
        }
        .list{
            width: 40px;
            height: 60px;
            list-style: none;
            border: 2px solid black;
            display: none;
            position: absolute;
        }
        .list>li{
            width: 40px;
            height: 20px;
            text-align: center;
        }
        .list>li:hover{
            background-color: skyblue;
        }
    </style>
</head>
<body>
    <ul class="list">
        <li>111</li>
        <li>222</li>
        <li>333</li>
    </ul>
    <script>
        const list = document.querySelector('.list')
        document.addEventListener('contextmenu',(event)=>{
            // 这一步很重要，取消浏览器默认的右键菜单
            event.preventDefault()
            list.style.display = 'block'
            let x = event.clientX
            let y = event.clientY

            // 判断一下，如果出现了菜单栏宽度加上clientX大于视口宽度的情况，则让x为固定值。竖直方向同理
            x = x>=document.documentElement.clientWidth-list.offsetWidth?document.documentElement.clientWidth-list.offsetWidth:x
            y = y>=document.documentElement.clientHeight-list.offsetHeight?document.documentElement.clientHeight-list.offsetHeight:y

            list.style.left = x+'px'
            list.style.top = y+'px'
        })

        // 给document加一个单击事件，让菜单栏消失
        document.addEventListener('click',(e)=>{
            list.style.display = 'none'
        })

        // 阻止冒泡，防止用户点击了菜单栏里的内容结果菜单栏因为冒泡消失了
        list.onclick = (e)=>{
            e.stopPropagation()
        }
    </script>
</body>
</html>